ASP.NET:New Action doesn't work - asp.net

I have started a web api project and I am trying to add a new action to my existing controller. Here is my controller code and configurations:
namespace QAServices.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
//[Route("Home/Welcome")] I have also tried this but it doesn't work.
public HttpResponseMessage Welcome()
{
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
return response;
}
public ActionResult ProductPage()
{
return View();
}
}
}
RouteConfig
namespace QAServices
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
WebApiConfig
namespace QAServices
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { action = "GET", id = RouteParameter.Optional }
);
}
}
}
When I try to run my new action I am having following error:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:1095/Home/Welcome'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'Home'.
</MessageDetail>
</Error>
I have followed these but can't figure out what is wrong:
Attribute Routing in ASP.NET Web API 2
Getting Started with ASP.NET Web API 2 (C#)
Routing Basics in ASP.NET Web API
Getting Started with ASP.NET MVC 5

Your code works for me. I get the response StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: , Headers: { }.
Your HomeController is just a regular MVC controller. However, the response you are getting appears to be a WebApi response. So it seems to indicate that the request is being routed to an ApiController.
Is it possible you have an ApiController in your project that is decorated with [RoutePrefix("Home")] which has no Welcome action method?
Also, if you have a mix of ApiController and MVC Controller, I would leave the default WebApiConfig route template of api/{controller}/{id} or at least differentiate if from that used for MVC controller.

Change public HttpResponseMessage Welcome() to public ActionResult Welcome(). In ASP.NET MVC controller actions need to return ActionResult.

Related

Mvc customize routes

I just want to customize routes in asp.net mvc ,
This is a blog website and I want to access controller methods using
wwww.sitename.com/blog/{blogtitle}
www.sitename.com/blog/{action}
Blog Controller
public class BlogController : Controller
{
public ActionResult Index(string title)
{
return View();
}
[Route("post-blog")]
[HttpPost]
public ActionResult Post(Blog blog,HttpPostedFileBase blogimage)
{
//some coe
}
[Route("post-blog")]
public ActionResult Post()
{
if (Request.Cookies["userInfo"]==null)
{
return Redirect("/login");
}
return View();
}
}
Here is route Config
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.Canonicalize().Www();
routes.Canonicalize().Lowercase();
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "freelogomaker", id = UrlParameter.Optional }
);
}
But I am unable to hit action name "Index" using www.site.com/blog/titlename
But I can access "post-blog" using www.site.com/blog/post-blog
Please help me I am beginner in asp.net mvc routing.
Add your parameter to the route attribute within {} brackets to indicate that it should be read from the URL, and not from something else (such as POST body, dependency injections, etc)
[Route("{title}")]
public ActionResult Index(string title)
{
return View();
}
I also like to add the RoutePrefix attribute to the controller to make it a bit clearer.
[RoutePrefix("blog")]
public class BlogController : Controller

can we pass null in the url parameter?

I have a Asp.Net webApi controller as below:
[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{
[Route("GetDetails/{id}")]
public HttpResponseMessage Get(string id)
{
// get business details code.
}
}
Is there anyway that client can hit this api with id null??
It depends on your configuration of Web API routes in App_Start/WebApiConfig.cs.
If route is something like:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "business/api/v1/GetDetails/{id}",
defaults: new { id = RouteParameter.Optional }
);
then user can reach resource use http://localhost.business/api/v1/GetDetails or http://localhost.business/api/v1/GetDetails/1.
When you remove defaults: new { id = RouteParameter.Optional } then user have to pass an id otherwise, it will return 404
Please try:
[RoutePrefix("business/api/v1")]
public class BusinessController : ApiController
{
[Route("GetDetails/{id:int?}")]
public HttpResponseMessage Get(int id)
{
// get business details code.
}
}

Working with WebApi in a Web Forms application

I am trying to add WebApi in my Web Forms application (Visual Studio 2015, .NET 4.6). I added App_Start folder and WebApiConfig.cs in it as following (pretty much copied from an MVC app):
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Adding routes for WebApi controllers
RouteTable.Routes.MapHttpRoute(
name: "SearchApi",
routeTemplate: "api/search",
defaults: new { controller = "SearchController" }
);
}
}
Then, I created a folder Controllers/WebApi and added SearchController.cs:
namespace IdeaMaverick.Web.Controllers.WebApi
{
public class SearchController : ApiController
{
public IEnumerable<string> Get()
{
return new [] { "value1", "value2" };
}
}
}
But when I hit http://example.com/api/search in the browser, I get this error:
{"message":"No HTTP resource was found that matches the request URI
'http://www.example.com/api/search'.","messageDetail":"No type
was found that matches the controller named 'SearchController'."}
I'm obviously missing something but I can't figure out what.
I found the issue - in defaults for the route I had to specify the controller name omitting "Controller", so it has to be like
defaults: new { controller = "Search" }

Asp.net web api routing to be like mvc site

How can I add a route so that my controllers will work similar to a mvc web appliation.
Because the default way that they have configured the routes will end up with you having so many controllers.
I just want to have a controller called Auth,
and then in my web API be able to call api/auth/login or api/auth/logout etc.
Because with the default routing I will have to create a controller for login and one for logout.
So then I would have my Controller like so:
public class AuthController : ApiController
{
[HttpPost]
public IEnumerable<string> Login()
{
return new string[] { "value1", "value2" };
}
[HttpGet]
public HttpMessageHandler Logout()
{
return new HttpMessageHandler.
}
}
The default Web API route uses the http method to determine the action to select. For example POST api/auth would look for an action named Post on AuthController.
If you want to use RPC style routing (like MVC) you need to change the default route to:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Now POST api/auth/login will look for an action named Login on AuthController.

Routing in ASP .NET Web API

I created a web service using WEB API.
I'm using this routing configuration
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
And my solution include two controller (ProductController and DetailController)
So when I want to call a WS that refers to the GetDetails method(is located inside DetailController) I have to use a URL like this:
http://localhost/api/Details/GetDetails/?id=4
Is there a way for use, for the same request, this URL instead:
http://localhost/api/Product/GetDetails/?id=4
letting the GetDetails method inside the DetailController?
Actually your urls should be:
http://localhost/api/Details/4
http://localhost/api/Products/4
and your controllers:
public class DetailsController: ApiController
{
public HttpResponseMessage Get(int id)
{
...
}
}
and:
public class ProductsController: ApiController
{
public HttpResponseMessage Get(int id)
{
...
}
}
Now that's RESTful.

Resources