Mvc http post method gives me "The resource cannot be found. " - asp.net-mvc

here is my root controller :
[HttpPost]
public ActionResult Index()
{
}
but it couldn't load project it give me :
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Try this
public ActionResult Index()
{
}
[HttpPost, ActionName("Index")]
public ActionResult IndexPost()
{
}
The ActionName attribute enables you to create a method of one name that relates to another

Related

odataroute same name for post and get

I am having one controller Name MailingAddress and in starup.cs i had used below code to set odataroute .If i am specifying same odataroute for building 2 entitys i am getting run time error .How can we build two entityes with same odata route so that get and post will be called with same name?
builder.EntitySet<BEAccountAddresses>("MailingAddresses");
builder.EntitySet<BEMailingAddressesRequest>("MailingAddresses");
[HttpPost]
[ODataRoute("MailingAddress")]
public BEMailingAddressConfirmation AddMailingAddresses(BEMailingAddressesRequest beMailingAddressesRequest)
[HttpGet]
[EnableQuery]
[ODataRoute("MailingAddresses({key})")]enter `enter code here`code here
public BEAccountAddresses Get([FromODataUri]string key)

Action Name not showing Up In URL

I am trying to create a form in a view and am running into trouble with the routing; it seems to be totally ignoring the action name that I am providing. Here are my controller methods (Controller is called "MyController"):
[HttpGet]
public ActionResult CreateNewRequest()
{
if (ModelState.IsValid)
{
MyViewModelClass model = new MyViewModelClass();
return View("CreateNewRequest", model);
}
else
{
return DisplayModelStateError(ModelState.Values);
}
}
[HttpPost]
public ActionResult CreateNewRequest(MyViewModelClass model)
{
//code to process the view model
return RedirectToAction("Index");
}
In my view, I have tried several variations of the same thing to render a form, including:
#using (Html.BeginForm("CreateNewRequest","My",FormMethod.Post))
#using (Html.BeginForm("CreateNewRequest","My"))
#using (Html.BeginForm("CreateNewRequest","My",null,FormMethod.Post))
They all fail when the user clicks the submit button; I get an error that says:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /My
What is especially odd is that if i reverse them (which I know to be incorrect), I get an error message implying it looked for the action as opposed to totally ignoring it. For example, if I try
#using (Html.BeginForm("My","CreateNewRequest",FormMethod.Post))
I get the following error message:
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /CreateNewRequest/My
Any ideas here?

Attribute routing is failing for MVC/WebApi combo project

I am trying to create an ASP.NET app that is both MVC and Web Api. The default controller (HomeController) returns a view that is composed of some HTML and jQuery. I would like to use the jQuery to call the API that is part of the same project.
I have the API setup and have been testing it with Postman but I get the following error when trying to reach the endpoints in the API.
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:19925/api/encryption/encrypt'.",
"MessageDetail": "No action was found on the controller 'Values' that matches the request."
}
I am attempting to use attribute routing so I am pretty sure that is where I am going wrong.
[RoutePrefix("api/encryption")]
public class ValuesController : ApiController
{
[HttpPost]
[Route("encrypt")]
public IHttpActionResult EncryptText(string plainText, string keyPassPhrase)
{
// Method details here
return Ok(cipherText);
}
}
I have the route prefix set to api/encryption. I also have the method using the route encrypt and marked as a HttpPost. Below is my WebApiConfig which I think is configured properly for attribute routing.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
// Default MVC routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
By my understanding a POST to the following URL should reach the method ..
http://localhost:19925/api/encryption/encrypt
yet it isn't. I am posting the two string values to the method via Postman. I have attached a screen capture (and yes the keyPassPhrase is fake).
Here is the global.asax as requested ...
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
One other thing to note ... that when I change from GET to POST in Postman it works .. as long as I am sending the parameters along in the query string. If I send the parameters in the body I get the original error.
The problem was that I was trying to POST two values to an API method that accepted two parameters. This is not possible with the API (well not without some work arounds) as the API method is expecting an object rather than two different primitive types (i.e. String).
This means on the server side I needed to create a simple class that held the values I wanted to pass. For example ...
public class EncryptionPayload
{
public string PlainText { get; set; }
public string PassPhrase { get; set; }
}
I then modified my API method to accept a type of this class
[Route("encrypt")]
[HttpPost]
public IHttpActionResult EncryptText(EncryptionPayload payload)
{
string plainText = payload.PlainText;
string passPhrase = payload.PassPhrase
// Do encryption stuff here
return Ok(cipherText);
}
Then inside that controller I pulled the Strings I needed from the EncryptionPayload class instance. On the client side I needed to send my data as a JSON string like this ..
{"plainText":"this is some plain text","passPhrase":"abcdefghijklmnopqrstuvwxyz"}
After changing these things everything worked in Postman. In the end I wasn't taking into account Model Binding, thinking instead that an API endpoint that accepted POST could accept multiple primitive values.
This post from Rick Strahl helped me figure it out. This page from Microsoft on Parameter Binding also explains it by saying At most one parameter is allowed to read from the message body.
Try the following code. It will work :
[RoutePrefix("api/encryption")]
public class ValuesController : ApiController
{
[Route("encrypt"),HttpPost]
public IHttpActionResult EncryptText(string plainText, string keyPassPhrase)
{
// Method details here
return Ok(cipherText);
}
}
Sorry dear it was really compile time error. I edit my code. Please copy it and paste it in yourcode. Mark as answer If i Helped.

RediretAction in MVC causes "The Web server is configured to not list the contents of this directory"

I have a contentController like this :
public class ContentController : Controller
{
public ActionResult Index()
{
var model = obj.GetContentlist();
return View(model);
}
[HttpPost]
public ActionResult Create(Content content)
{
obj.AddNewContent(content);
obj.Save();
return RedirectToAction("Index","content");
}
}
That as you can see contains create action .But in the last line ,when it is going to be executed RedirectToAction("Index","content"); i got this error :
HTTP Error 403.14 - Forbidden
The Web server is configured to not list the contents of this directory.
Most likely causes:
A default document is not configured for the requested URL, and directory browsing is not enabled on the server.
The default MVC template includes a "Content" folder. Since you're redirecting to content/index and index is most likely the default action, you actually get redirected to /content -- which is the content directory rather than your controller. If I were you I would choose another name for your controller to avoid the conflict.

How can I set up my default view in MVC4 to point to a specific area, controller and action?

I have a User area and inside this I have the following registered:
context.MapRoute("DefaultRedirect",
"",
new { controller = "Account", action = "Login" }
);
When I use routeDebug it tells me that when I connect to my site www.xxx.com then it will try to call
area = User, controller = Account, action = Login
When I connect directly using: www.xxx.com/User/Account/Login my login page appears.
When I don't use routeDebug and connect to my site www.xxx.com then I get an error message saying:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
Here's my controller action method:
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login()
{
ViewBag.ReturnUrl = "xx";
return View("~/Areas/User/Views/Account/Login.cshtml");
}
I am very confused as routeDebug appears to show I am going to the right controller and action however when I don't use that and place a breakpoint it does not seem to go to the controller action.
if this controller is inside the same area i think you just can use
[AllowAnonymous]
public ActionResult Login()
{
ViewBag.ReturnUrl = "xx";
return View();
}
Either way if you have only the views on a different areas you can use
return View("~/Views/YourArea/YourController/YourView.aspx");
return RedirectToAction("Login", "Account");
Will redirect to specific controller and specific action.
If account is deeper in folders just include the path

Resources