System.Web.HttpException (0x80004005): Maximum request length exceeded - asp.net-mvc

I am trying to upload an mp4 video file that is 5.25 MB in size in an ASP.NET MVC 5 application.
I have tried adding this to the Web.config file which has been the accepted answer in most cases to this problem.
<system.web>
<!-- This will handle requests up to 1024MB (1GB) -->
<httpRuntime maxRequestLength="1048576" />
</system.web>
I've also tried setting the timeout as well in the Web.config
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
However, when I go to upload the file I am getting System.Web.HttpException (0x80004005): Maximum request length exceeded.
Maybe there is something that needs to be set in the controller or view?
Controller:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
if (fileName != null)
{
var path = Path.Combine(Server.MapPath("~/Content/Videos"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
View:
#using (Html.BeginForm("Edit", "Posts", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="OK" />
}
How do you upload video files in ASP.NET MVC 5?

Try add this in web.config (in bytes !):
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>

Related

IIS CORS multiple domain

How enable multiple domains for Access-Control-Allow-Origin?
I have one application (ASP .NET MVC) binded to example.com and www.example.com
Next code not valid.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://example.com,http://www.example.com" />
<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
Valid or http://example.com or http://example.com
I need both
private void GlobalBeginRequest(object sender, EventArgs e)
{
var Origins = "domain1.com,domain2.com,domain3.com:8081";
if ((Request.Headers["Origin"] != null) && (Origins.Split(',').FirstOrDefault(x => Request.Headers["Origin"].Contains(x)) != null))
{
Response.Headers.Add("Access-Control-Allow-Origin", String.Format("{0}", Request.Headers["Origin"]));
}
}

Remote validation isn't working in mvc.

I am using remote validator but it's not working even debugger isn't tracing that method.
public JsonResult CheckStrategyName(string StrategyName)
{
var ab = from a in db.Sterategy where a.StrategyName == StrategyName select a.StrategyName;
return !ab.Any() ? Json(true, JsonRequestBehavior.AllowGet) : Json(string.Format("Name Already esists"), JsonRequestBehavior.AllowGet);
}
I have used it here
[Required]
[Remote("CheckStrategyName", "St", ErrorMessage = "Already exists ")]
[Display(Name = "Name")]
public string StrategyName { get; set; }
Webconfig
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Where am I making mistake ? :(
Your server code & settings seems to be fine. Make sure the following are in place
You are using the TextBoxFor helper method to generate the relevant input field markup and it is inside a form.
#using (Html.BeginForm())
{
#Html.TextBoxFor(s => s.StrategyName)
#Html.ValidationMessageFor(s => s.StrategyName)
<input type="submit" value="Submit" />
}
You have included the javascript libraries needed for validation.
<script src="~/Scripts/jquery.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

AngularJS $http.put doesn't work with ASP.NET MVC controller

I am trying to create simple page where I am sending some data to the server using $http.put.
Script code
<script>
var myApp = angular.module("myApp", []);
myApp.controller("HttpPostController", function ($scope, $http) {
$scope.SendHttpPostData = function () {
var data = $.param({
firstName: $scope.firstName,
lastName: $scope.lastName,
age : $scope.age
});
$http.put('/ServerRequest/PutDataResponse', data)
.success(function (data, status, headers, config) {
$scope.ServerResponse = data;
})
.error(function (data, status, header, config) {
$scope.ServerResponse = htmlDecode("Data: " + data +
"\n\n\n\nstatus: " + status +
"\n\n\n\nheaders: " + header +
"\n\n\n\nconfig: " + config);
});
};
});</script>
My HTML code
<div ng-app="myApp" ng-controller="HttpPostController">
<form ng-submit="SendHttpPostData()">
<p>First Name: <input type="text" name="firstName" ng-model="firstName" required /></p>
<p>Last Name: <input type="text" name="lastName" ng-model="lastName" required /></p>
<p>Age : <input type="number" name="age" ng-model="age" required /></p>
<input type="submit" value="Submit" />
<hr />
{{ ServerResponse }}
</form></div>
ASP.NET MVC controller action method
[HttpPut]
public ContentResult PutDataResponse(string firstName, string lastName, int age)
{
return Content("First name: " + firstName +
" | Last name: " + lastName +
" | Age: " + age +
" | Request Type: " + Request.RequestType.ToString());
}
The error message I get is following
TTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. Most likely causes: The directory or file specified does not exist on the Web server. The URL contains a typographical error. A custom filter or module, such as URLScan, restricts access to the file. Things you can try: Create the content on the Web server. Review the browser URL. Check the failed request tracing log and see which module is calling SetStatus.
So in ASP.NET MVC it doesn't work. (POST and GET works). I tried the above with ASP.NET MVC Web API and it works fine. I am able to send and receive response using PUT method of mvc web api.
The question is why it doesn't work in ASP.NET MVC even if the method verb is [HttpPut].
Thanks
Okay, after much effort I found the solution. Actually, the problem was that by default ASP.NET MVC doesn't allow "PUT" or "DELETE" request type so we need to enable them in the web.config file like below.
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<remove name="FormsAuthenticationModule" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
Notice the ExtensionlessUrlHandler-Integrated-4.0 handler. This makes the difference. This is allowing all types of verb acceptable and so even PUT request now works with ASP.NET MVC.
I suspect the model binding works differently. You are passing in :
var data = $.param({
firstName: $scope.firstName,
lastName: $scope.lastName,
age : $scope.age
});
An object with 3 properties. Yet your MVC controller method is looking for 3 parameters only: string firstName, string lastName, int age
You could change your MSC controller method to expect an object with 3 properties i.e:
public class myViewModel
{
string firstName;
string lastName;
int age;
}
public ContentResult PutDataResponse(myViewModel formData)
or
Change the request to pass the parameters in the URL:
$http.get('/ServerRequest/PutDataResponse?firstname=bob&lastname=smith&age=12')
Also, check your route : '/ServerRequest/PutDataResponse' . If you are using default routing, This will map to Your /ServerRequestController and the first HttpPut method. From your example I don't know if you have more than one HttpPut method on your controller. If you do, you could add an attribute route [Route("ServerRequest/PutDataResponse")] to the top of your MVC method.

How to add an profile field using ASP.Net membership provider?

I am working on an app using the ASP.NET membership provider. By default, i can use a few fields such as username, password. How to add to the asp.net membership provider so I can add Profile fields such as "firstName", "lastName" in the register section and have it save to the database in aspnet_profile table along with other data.
I am creating a user in the account model as below:
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password,
model.Email,model.PasswordQuestion,model.PasswordAnswer,
true, null,out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
return View(model);
}
Now which function i should use to store profile info into db?
Help me !!
Add the fields to the profile section of Web.Config.
<profile>
<properties>
<add name="FirstName" />
<add name="LastName" />
<add name="Address1" />
<add name="Address2" />
<add name="City" />
<add name="State" />
<add name="Zip" />
<add name="Phone" />
<add name="ProfileVersion" type="int" defaultValue="0" />
</properties>
</profile>
For more information please visit: http://msdn.microsoft.com/en-us/magazine/cc163457.aspx

Remote Validation in ASP.NET MVC 3

I am trying to get remote validation working in ASP.NET MVC 3 but for some reason the validation never gets fired. I am returning json from the controller and in FireFox it ask me to download the files. Not sure what is going on here. Here is my code:
#using(Html.BeginForm(new {Action = "ValidateUserName"})) {
<text> Enter UserName: </text> #Html.TextBoxFor(x => x.UserName)
<input type="submit" value="Login" />
}
Here is the RegistrationViewModel:
public class RegistrationViewModel
{
[Required(ErrorMessage = "UserName is required!")]
[Remote("ValidateUserName","Home",ErrorMessage ="UserName already taken!")]
public string UserName { get; set; }
}
And here is the HomeController:
public ActionResult ValidateUserName(RegistrationViewModel registrationViewModel)
{
return Json(!registrationViewModel.UserName.Equals("test"),JsonRequestBehavior.AllowGet);
}
A couple of things to consider:
1) In your view, you should be referencing the jquery validation and unobtrusive javascript libraries:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
2) Also in your view, you should have an Html.ValidationMessageFor(m => m.Attribute):
#Html.ValidationMessageFor(x => x.UserName)
3) Lastly, make sure you have the two AppSettings in your web.config file that enable the client-side validation.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

Resources