Description: HTTP 404 for JSON return - c#

i'm kinda new to programming c# and asp.net, i just want to build a rest api for my android app to sign in and sign up. but i face a problem for sign in (login).
the problem is i just wrote this codes below:
namespace CPanel.Controllers
{
public class DashboardController : Controller
{
// GET: Dashboard
public ActionResult CreateUser()
{
return View();
}
[HttpPost]
public ActionResult CreateUser(string username,string password)
{
CPanel.Models.CPanelEntities1 db = new Models.CPanelEntities1();
db.USP_AddUSer(username, password);
return View();
}
[HttpPost]
public ActionResult login(string username,string password)
{
CPanel.Models.CPanelEntities1 db = new Models.CPanelEntities1();
try
{
var user = db.USP_Authenticate(username, password).First();
return Json(new { UserId = user.UserId,Username=user.Username,IsAdmin=user.IsAdmin,Message="ok"});
}catch(Exception)
{
return Json(new { message = "error" });
}
}
}
}
the first part (CreateUser) work perfectly. but second part (login) only work on "Postman" chrome application.
i post a request on "Postman" -
localhost/dashboard/login?username=php&password=php
and i see a json:
{
"UserId": 29,
"Username": "php",
"IsAdmin": false,
"Message": "ok"
}
in localhost and wwwroot (iis) there in no chance and i face this error:
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: /dashboard/login
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.6.1586.0

When you enter the http://localhost/dashboard/login?username=php&password=php url to web browser it issues a GET request, however your controller only accepts POST requests.
There's another thing, as far as I understand you need a web api but your example is a standard ASP.NET MVC controller. You might want to take a look on the following tutorial: https://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

Related

ASP.NET Core API - View is not displayed after redirect from Api Controller

I am having some troubles while redirecting from Api Controller to Controller. I can see in postman response, that correct View is returned.
public class ApiController : Controller
{
[HttpPost("/someApiAction/{id}")]
public async Task<IActionResult> SomeApiAction(string id)
{
return RedirectToAction("Action", "Other", new { id = id});
}
}
Other Controller:
public class OtherController : Controller
{
public async Task<IActionResult> Action(string id)
{
var model = new Model();
return View(model);
}
}
Code reaches return View(model) but it's not displayed.
Can anybody please help on this one?
I assume you are requesting the web api controller from PostMan instead of Html page. For check the page from Postman, you need to copy the content out and view it from browser by view html online site.
For Postman, it will not be able to open web browser from the response.
Try to check the html by request the api controller like code below:
<form asp-controller="UserApi" asp-action="SomeApiAction" asp-route-id="2" formmethod="post">
<button type="submit">Request Api</button>
</form>

C# MVC5 Present string url in view

I am beginning developer in asp.Net MVC5.
In my MVC project i use with web service that return me a string URL the URL is from another domain.
I want to move to the URL.
For clear myself:
The client fill form home page and press submit, in the server side i send a request web
service with parameters from the form and get URL with another domain and this URL i need to present as second page to the client
public class HomeController : Controller
{
public ActionResult Home()
{
return View("~/Views/Home/home.cshtml");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult doSomething(Something obj)
{
//use web service and get string URL
string urlString = ;// get from the web service response.
return View();// want write in the ();
}
}
Also this is usefull for navigation in MVC.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult doSomething(Something obj)
{
//use web service and get string URL
string urlString = ;// get from the web service response.
if (!string.IsNullOrEmpty(urlString))
{
//if the url is from within the domain.
return RedirectToAction(urlString);
//if the url is from other domain use this
//return Redirect(urlString);
}
//If the urlString is empty Return to a error page
return View("Error");
}
The url is from another site not the same domain
If you want to redirect to an external URL, you will need to use the Redirect() method.
Like so:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DoSomething(Something obj)
{
// Use web service to get the string URL
string urlString = ...;
if (string.IsNullOrEmpty(urlString))
{
// If the urlString is empty, take the user to an Error View.
return View("Error");
}
// Redirect the user to the urlString
return Redirect(urlString);
}
I would recommend also doing some checking to ensure the URL is definitely valid. You can do this using the Uri static method, IsWellFormedUriString() - this returns a bool.
Like so:
if (!Uri.IsWellFormedUriString(urlString, UrlKind.Absolute))
{
// If the urlString is not a well-formed Uri, take the user to an Error View
return View("Error");
}
// Redirect the user to the urlString
return Redirect(urlString);
Alternatively, if you're redirecting to an internal Action, use the RedirectToAction() method, as #ankur suggested.
As an extra note: Ensure that your C# method names use PascalCase. Conserve camelCase for local variables/private fields.
So, you would use DoSomething(...), instead of doSomething(...) (I've done this in my example).
Hope this helps.

Redirect from APIController action to other MVC controller action

I created a web api controller that has an register action:
public class MyProjApiController : ApiController
{
public IHttpActionResult Register()
{
return RedirectToAction("Register", "AccountController"); //??
}
}
And I am trying to redirect to another action in MVC Controller public class AccountController : Controller that has public async Task<ActionResult> Register(RegVM model) but my Register action in MyProjApiController has IHttpActionResult return type and register in AccountController has Task<ActionResult> type - how to call it?
I think you are mixing two concepts here. Your API controller should have endpoints which will be called from some client and you should be returning some data back in a format which client can read, XML or JSON. You should not be doing a redirect to another MVC controller.
What you should be doing is return some data which has the path to the MVC action controller which the client can use.
public HttpResponseMessage Register()
{
//DO something as you want
var newUrl = this.Url.Link("Default", new { Controller = "Account",
Action = "Register" });
return Request.CreateResponse(HttpStatusCode.OK,
new {Success = true, RedirectUrl = newUrl});
}
This will return you a response like this to the caller with 200 OK response status code
{
"Success" : true,
"RedirectUrl" : "yoursite.com/Account/Register"
}
The client should read this and do the necessary things. For example, If you are calling this API from your js code, You can simply use window.location.href to redirect the user to the new page.
For example ,
$.post("PathToYourApiEndpoint",function(res){
if(res.Success)
{
window.location.href = res.RedirectUrl;
}
});
Again,I am not sure why you are calling the API first and the redirecting the user to the MVC controller action. Whatever logic you are doing in the Web api action method, you might be able to do in your MVC controller and thus avoid your API call.
If you mean from the API help file. I wanted to disable except for local.
if (!Request.IsLocal)
{
Response.Redirect("/home");
}

Facebook Deauthorization ASP.NET Web API

I have been through all of the posts about the Facebook deauthorization url and none of them address my issue. I an have ASP.Net Web Api 2 endpoint, but I cannot get the ping to come through correctly. Here is what my Route signature looks like:
[AllowAnonymous, Route("FacebookDeauthorize"), HttpPost]
public async Task<IHttpActionResult> FacebookDeauthorize(string signed_request)
{
//code for reading it
}
This results in a 404, so I tried changing the type to object and getting the type so i could figure out what it was coming through as. It threw a null reference exception when i tried access the object, so I think its just not coming through at all. Since this is Web API, I can't look to the request for a form to get the signed request from. Has anyone successfully gotten this to work with Web Api? Any help/pointers as to what the route signature should be?
For anyone else who finds this, here is the working endpoint for asp.net web api and the Facebook c# sdk, trick is to use a model and not a primitive:
public class FacebookDeauthModel
{
public string signed_request { get; set; }
}
[AllowAnonymous]
[Route("FacebookDeauthorize")]
[HttpPost]
public async Task<IHttpActionResult> FacebookDeauthorize(FacebookDeauthModel model)
{
FacebookClient fb = new FacebookClient();
dynamic signedRequest = JsonConvert.DeserializeObject(fb.ParseSignedRequest("YOUR_APP_SECRET", model.signed_request).ToString());
string FBUserID = signedRequest.user_id;
ApplicationUser user = UserManager.FindBy(x => x.FBAppID == FBUserID);
if (user != null)
{
user.IsActive = false;
user.InactiveReason = "Facebook deauthorized on " + DateTime.UtcNow;
await UserManager.UpdateAsync(user);
}
else
{
_tracer.Error(Request, "FacebookDeauthorize", "Facebook tried to deauthorize a user we do not have record of, FBAppID: {0}", FBUserID);
}
return Ok();
}

oauth redirecting in asp.net mvc4

I will try to implement redirect with oauth authorization in asp.net mvc4 project
controller
public ActionResult SomeName() {
if (!User.Identity.IsAuthenticated) {
return RedirectToAction("ExternalLogin", "Account", new { provider = "vkontakte" });
}
}
account
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider) {
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback"));
}
error
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: /Account/ExternalLogin
Does anybody know what I should to do?
try this:
[HttpGet]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider) {
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback"));
}
By using RedirectToAction you are making a GET request to the url of your action, you need to accept HttpGet at ExternalLogin action on your AccountController
RedirectToAction is 302 redirect request which is GET by nature. if you are supposed to utilize your action from VIEW as well, you can use both verbs :
[HttpGet, HttpPost]
at ExternalLogin action on your AccountController accept HttpGet as other member also said.

Categories

Resources