ASP.NET MVC 3 Application Not working - c#

Im passing the URL like "http://localhost:6384/Name/4:" But this is get an error.
Controller Method :
//
// GET: /Name/5
public string SetName(int id)
{
return "You entered: " + id;
}
Error:
Server Error in '/' Application.
HTTP Error 400 - Bad Request.
Version Information: ASP.NET Development Server 10.0.0.0
Please Help Me!!!

Verify following steps,
1) In global.axas verify the default root as follows,
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
2) Mention controller name in the url , if you controller and action is as follows
public class HomeController : Controller
{
public ActionResult SetName(int id)
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
then url will be ,
http://localhost:6384/Home/SetName/4

You should try this:
public ActionResult SetName(int id) {
return Content("You entered: " id);
}
Sorry, it was easier than that. You're entering the URL incorrect. You have not specified the controller name.
http://localhost:6384/CONTROLLERNAME/SetName/4

In this error message.
HTTP Status 400 Bad Request - Bad Syntax
Possibly, because the Action Result cannot found or not exist.
This is wrong action method:
// GET: /Name/5
public string SetName(int id)
{
return "You entered: " + id;
}
I will correct your action method:
[HttpGet]
public ActionResult Setname(int id)
{
ViewBag.Result = "You entered: " + id;
return View();
}

Related

Attribute Based Routing/Versioning in ASP.Net WEB API 2.0

I'm trying to use versioning in Asp.Net Web API.
Following is the structure of the project.
To support versioning I've added Microsoft.AspNet.WebApi.Versioning NuGet package.
Following is the code snippet of WebApiConfig:
public static void Register(HttpConfiguration config)
{
var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof(ApiVersionRouteConstraint)
}
};
config.MapHttpAttributeRoutes(constraintResolver);
config.AddApiVersioning();
// Web API configuration and services
// Web API routes
//config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
And below is the code from controller:
[ApiVersion("1.0")]
[RoutePrefix("api/v{version:apiVersion}/employeemanagement")]
public class EmployeeManagementController : ApiController
{
[Route("GetTest")]
[HttpGet]
public string GetTest()
{
return "Hello World";
}
[Route("GetTest2")]
[HttpGet]
public string GetTest2()
{
return "Another Hello World";
}
[Route("saveemployeedata")]
[HttpPost]
public async Task<GenericResponse<int>> SaveEmployeeData(EmployeeData employeeData, ApiVersion apiVersion)
{
//code goes here
}
[Route("updateemployeedata")]
[HttpPost]
public async Task<GenericResponse<int>> UpdateEmployeeData([FromBody]int id, ApiVersion apiVersion)
{
//code goes here
}
}
If I use [FromBody] in UpdateEmployeeData, it gives following error:
{
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[AlphaTest.API.Models.ResponseModels.GenericResponse`1[System.Int32]] UpdateEmployeeData(Int32, Microsoft.Web.Http.ApiVersion)' in 'AlphaTest.API.Controllers.V1.EmployeeManagementController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
Following is the URL & data, I'm passing to generate above error:
http://localhost:53963/api/v1.0/EmployeeManagement/updateemployeedata
If I remove[FromBody] it gives me 404 Not found error.
Please help me understand what I'm doing wrong here, which is causing above mentioned error.
You could use object that contains property called Id as parameter of the action UpdateEmployeeData not directly the int Id, like :
public class Request
{
public int Id { get; set; }
}
The action will be :
[Route("updateemployeedata")]
[HttpPost]
public async Task<GenericResponse<int>> UpdateEmployeeData([FromBody]Request request, ApiVersion apiVersion)
{
//code goes here
}
I hope you find this helpful.

How can I force the Route with .html and id?

I wanna force the Route with .html and a 32 length id.
For example, here is the URL:
https://localhost:44331/Re/test.html?id=12345678901234567890123456789012
I want it when there is no id parameter in the URL or the length of id is not 32, it returns 404 status code.
Here is the controller:
namespace V.Controllers
{
[Route("Re/")]
public class ReController : Controller
{
[Route("test.html{id:length(32)}")]
public IActionResult test(string id)
{
return View();
}
}
}
After I ran the code, it always reports 404 status code.
What's wrong with my route?
I don't think you can specify query string parameters in the route. Try validating the id in the action, or if you can change the route, add it as an additional segment.
[Route("Re/")]
public class ReController : Controller
{
[Route("test.html")]
public IActionResult test(string id)
{
if (id == null || id.Length != 32)
return NotFound();
return Json(new {id= id});
}
[Route("test2.html/{id:length(32)}")]
public IActionResult test2(string id)
{
return Json(new {id= id});
}
}
See: Microsoft Docs

Setting up mvc route

I'm trying to create a mvc application. I have a project controller, actions are below
[AllowAnonymous]
[HttpGet]
public ActionResult Index()
{
//TODO: Browse
return View();
}
[AllowAnonymous]
[HttpGet]
public ActionResult Index(long projectId)
{
using (var entity = new dixraContext())
{
var project = entity.Projects.FirstOrDefault(m => m.Id == projectId);
if (project == null)
return RedirectToAction("NotFound", "Error");
else
return RedirectToAction("Index", project.UrlName);
}
}
[AllowAnonymous]
[HttpGet]
public ActionResult Index(string projectName)
{
using (var entity = new dixraContext())
{
var project = entity.Projects.Where(m => m.Name == projectName);
return View(project);
}
}
I want to show URL's like
example.com/Project/ProjectName
But when i enter url as
example.com/Project/1
Got Error.
An error occurred while processing your request
. as response. When i enter example.com/Project/Index/1 i go into first action.
I also want to resolve project from id and redirect to usual Project/ProjectName url.
Looks like you've got conflicting routes. One way to solve this while leaving your three possible inputs would be checking your input parameter.
Also, your RedirectToAction has a string as its second parameter - that overload of RedirectToAction treats the second parameter as the controller name, not the route object:
Assuming your routes file looks ok:
routes.MapRoute(
name: "Project",
url: "Project/{projectName}",
defaults: new { controller = "Project", action = "Index" }
);
Your controller action might be:
[AllowAnonymous]
[HttpGet]
public ActionResult Index(string projectName)
{
if (string.IsNullOrWhiteSpace(projectName))
{
// return your empty view
}
int projectId;
if (int.TryParse(projectName, out projectId))
{
projectName = GetProjectNameFromDatabase(projectId);
return RedirectToAction("Index", new { projectName });
}
// return your view with your model
}
There may be a better way, but this will work.

Route to user's page under the dynamic username path in MVC4

I have some dynamic user route like
routes.MapRoute(
"UserNames", // Route name
"{username}", // URL with parameters
new { controller = "Home", action = "UserName" });
and under the HomeController.cs
public ActionResult UserName(string username)
{
ViewBag.Message = username;
return RedirectToAction("Register","Account"); // Test...
}
It is working fine.
But what I need is to get working the URL like
http:\\mywebsite.com\UserNameBob\MyGallery\1
http:\\mywebsite.com\UserNameBob\Profile
http:\\mywebsite.com\UserNameBob\MyFriends
How do I can archive it?
Any clu?
Thank you!!!
Do you mean something like this:
routes.MapRoute(
"UserNames", // Route name
"{username}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "UserName", id = UrlParameter.Optional });
And then in HomeController you put actions like these:
public ActionResult MyGallery(string username, int id) {
// code
}
public ActionResult Profile(string username) {
// code
}
EDIT: Of course, if the gallery ID is not an int, just use string or whatever is appropriate.
Look for URL Rewriting in ASP.NET to handle the dynamic parameters while routing.

MVC 3 routing for unknown urls

I want to be able to handle any url that s requested via some controller.
foo.com/a
foo.com/abcd
foo.com/x1
for foo.com/a
I want to process it with
UrlHandlerController with Process(string url) method.
How should i add a routing rule to be able to do this?
Any ideas?
Create a new custom route and use Phill Haack's Route Debugger to test your routes:
routes.MapRoute(
"customroute",
"{url}",
new { controller = "UrlHandler",
action = "Process",
url = ""
}
);
Controller:
public class UrlHandlerController : Controller
{
[HttpGet]
public ActionResult Process(string url)
{
return View();
/* or */
if(url == "something"){
return View("SomethingView");
}
else if(url == "somethingelse"){
return View("SomethingElseView");
}
}
}
Darth, see if this route helps:
routes.MapRoute(
"CustomRoute", // Route name
"{url}", //Route formation
new { controller = "UrlHandler", action = "Process" }, // Where to send it
new { keyWord = #"\S+" } // Regex to identify the argument
);
Regards.

Categories

Resources