First of all, I would like to apologize for my really bad english, if something is not understandable, then reask please.
When I try POST with /api/account/regapi in Swagger then with too short password it gives error 200, but with correct length it gives error 500, while debugging it shows correct parameters at AuthDTO model, but still shows error 500 with correct data.
Response header returned by false data(incorrect password length):
{
"$id": "1",
"succeeded": false,
"errors": [
{
"$id": "2",
"code": "PasswordTooShort",
"description": "Passwords must be at least 6 characters."
}
]
}
Response header with incorrect password
access-control-allow-origin: *
content-type: application/json; charset=utf-8
date: Sat, 26 May 2018 13:54:06 GMT
server: Kestrel
transfer-encoding: chunked
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?RDpcS29vbGkgQXNqYWRcVlIyXFZSMlByb2pla3RTb2x1dGlvblxWUjJQcm9qZWt0XGFwaVxBY2NvdW50XFJlZ0FwaQ==?=
Response header with correct data:
content-type: text/html; charset=utf-8
date: Sat, 26 May 2018 14:03:59 GMT
server: Kestrel
transfer-encoding: chunked
x-powered-by: ASP.NET
x-sourcefiles: =?UTF-8?B?RDpcS29vbGkgQXNqYWRcVlIyXFZSMlByb2pla3RTb2x1dGlvblxWUjJQcm9qZWt0XGFwaVxBY2NvdW50XFJlZ0FwaQ==?=
Registration in AccountController
public async Task<IActionResult> RegApi(AuthDTO model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
return Ok(result);
}
return BadRequest();
}
public class AuthDTO
{
public string Email { get; set; }
public string Password { get; set; }
}
I think the is problem is in _usermanager, because error 500 is starting to show up there
Related
I am trying to call a POST method of Moosend API from my MVC application. The Post call is working fine from Postman but throwing error from controller.
The Code goes as below:
public async Task<ActionResult> CreateEmailList()
{
try
{
using (var httpClient = new HttpClient { BaseAddress = new Uri(Baseurl) })
{
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
using (var content = new StringContent("{ \"Name\": \"APIList\"}", System.Text.Encoding.Default, "application/json"))
{
using (var response = await httpClient.PostAsync("Mailing Lists/lists/create.json?apikey=0000", content))
{
string responseData = await response.Content.ReadAsStringAsync();
}
}
return View();
}
}
catch (Exception ex)
{
return View();
}
}
The Error I am getting is as below:
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-Robots-Tag: noindex, nofollow
X-Server-ID: 2
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type, Accept, Cache-Control, X-Requested-With
Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE, PUT
Cache-Control: private
Date: Thu, 25 Nov 2021 06:58:44 GMT
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 5054
Content-Type: text/html; charset=utf-8
}}
Any suggestions on what am I missing here. Most of the POST example is similar to the code that I implemented.
I need to call an API from AppService by uri.
This is my API:
public ApiOutputBase Test_AddStudent(string name, int age, string address)
{
return new ApiOutputBase
{
Result = new Result { Status = true, Message = "OK,Test_AddStudent Done!" },
OuputValues = new List<object>() { name, age, address }
};
}
I use this Function to call it:
public async Task<bool> TestCallApi()
{
var client = new HttpClient { BaseAddress = new Uri("http://localhost/") };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var testJson = "{\r\n \"name\": \"MyName\",\r\n \"age\": 25,\r\n \"address\": \"MyAddress\"\r\n}";
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));
// Call api success
if (response.IsSuccessStatusCode)
{
}
return true;
}
I used Swagger to call Test_AddStudent successfully. The testJson was copied from Swagger when I call Test_AddStudent successfully.
After that, I used Swagger to call TestCallApi without any error, but when I tried to debug the value of HttpResponseMessage, it showed this error:
{
StatusCode: 400,
ReasonPhrase: 'Bad Request',
Version: 1.1,
Content: System.Net.Http.StreamContent,
Headers: {
Pragma: no-cache
Cache-Control: no-store, no-cache
Date: Tue, 31 Oct 2017 02:12:45 GMT
Set-Cookie: Abp.Localization.CultureName=en; expires=Thu, 31-Oct-2019 02:12:45 GMT; path=/
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Content-Length: 405
Content-Type: application/json; charset=utf-8
Expires: -1
}
}
Have I missed something?
I finally found the root cause: I passed the wrong input to the api:
Wrong:
var testJson = "{\r\n \"name\": \"MyName\",\r\n \"age\": 25,\r\n \"address\": \"MyAddress\"\r\n}";
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent", new StringContent(testJson));
Correct:
HttpResponseMessage response = await client.PostAsync("api/services/myApp/commonLookup/Test_AddStudent?name=MyName&age=25&address=MyAdress", "");
So I'm trying pass user data from one controller to another. I've been reading a lot about it here ---> http://www.dotnet-tricks.com/Tutorial/webapi/F2aL081113-Passing-multiple-complex-type-parameters-to-ASP.NET-Web-API.html and this guy seems to be doing exactly what I want to do, and he's using .PostAsJsonAsync to do it.
This is controller 1, which takes in user data and basically re-routes it to the other controller for authentication.
public ActionResult IDB(IDBUser i)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:64819");
HttpResponseMessage result = client.PostAsJsonAsync("/api/Participant/Authenticate", i).Result;
if (result.IsSuccessStatusCode)
{
return View();
}
else { // hits this breakpoint with 500 server error
return View("Index");
}
}
}
}
This seems to successfully make it to the other controller (below), as I'm getting a 500 error. However, I've got a breakpoint right at the beginning of the method, and it never seems to hit it.
[System.Web.Http.ActionName("Authenticate")]
[System.Web.Http.HttpPost]
public HttpResponseMessage Authenticate(IDBUser u)
{ //breakpoint it neve hits is on this line
bool Authenticate = false;
CredentialTester ct = new CredentialTester(u.password, u.username);
bool isAuthenticatedInt = ct.IntTest();
bool isAuthenticatedAcp = ct.AcpTest();
if (isAuthenticatedInt == true || isAuthenticatedAcp == true)
{
Authenticate = true;
return Request.CreateResponse(HttpStatusCode.OK, Authenticate);
}
else Authenticate = false;
return Request.CreateResponse(HttpStatusCode.NotAcceptable);
}
Any help is apprecitaed. Thanks everyone!
UPDATE
: I was able to look at the error and it is listed here:
{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{ Pragma: no-cache X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcYTU4NDYxOVxEb2N1bWVudHNcYXAxMDk1MTQtcWEtYXVvdG1hdGlvblxXaVFhLlZhbC1JZFxNVkNcV2lRYS5WYWwtSWQuV2ViU2VydmljZVxXaVFhLlZhbC1JZC5XZWJTZXJ2aWNlXFdpUWEuVmFsLUlkLldlYlNlcnZpY2VcYXBpXFBhcnRpY2lwYW50XEF1dGhlbnRpY2F0ZQ==?= Access-Control-Allow-Origin: * Access-Control-Allow-Headers: Content-Type, Accept Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS Cache-Control: no-cache Date: Thu, 12 May 2016 17:07:39 GMT Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Content-Length: 2307 Content-Type: application/json; charset=utf-8 Expires: -1}}
it looks like there's a problem with my Access- Control-Origin. I've put the appropriate adjustments in my web.config file (I've had a similar error before) but no luck.
Hi I try to call an web api by server side with:
using (var client = new HttpClient())
{
using (var rsp = client.PostAsJsonAsync<Request>(url, model).Result)
{
if (!rsp.IsSuccessStatusCode)
{
// throw an appropriate exception
}
var result = rsp.Content.ReadAsAsync<string>().Result;
}
}
but I get error
Error reading string. Unexpected token: StartObject. Path '', line 1, position 1.
If I try to call same url from jQuery
$.post('http://localhost/api/Test')
the server return
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Sun, 25 Oct 2015 12:15:56 GMT
Content-Length: 104
{
"Header": {
"Token": "Response",
"Timestamp": "2015-10-25T14:15:56.0092197+02:00"
}
}
The "model" arrive on api controller but I can't get response from request.
ReadAsAsync<T> attempts to deserialize the response to type T. In this case, you're saying you want to deserialize JSON to a string, which doesn't really make sense. Either use a type matching the response (i.e. a custom data structure containing Header, Token, etc.) or use ReadAsStringAsync() if you really want to get a string.
I have a MVC action filter that I use to validate my models that is giving me different responses on different versions of IIS. Here is the code for the action filter.
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var viewData = filterContext.Controller.ViewData;
var modelStateErrors = filterContext.Controller.ViewData.ModelState.Keys.SelectMany(key => filterContext.Controller.ViewData.ModelState[key].Errors);
string errorMessage;
if (modelStateErrors.Count() > 0)
{
ModelError error = modelStateErrors.FirstOrDefault();
if (error.ErrorMessage.IsNotNullOrEmpty())
{
errorMessage = error.ErrorMessage;
}
else if (error.Exception != null)
{
errorMessage = error.Exception.Message;
}
else
{
errorMessage = Messages.UNKNOWN_VALIDATION_ERROR;
}
}
else
{
errorMessage = Messages.UNKNOWN_VALIDATION_ERROR;
}
if (!viewData.ModelState.IsValid)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
filterContext.Result = new ContentResult { Content = errorMessage, ContentType = "text/plain" };
}
else
{
var controller = filterContext.Controller as WMSControllerBase;
if (controller != null)
{
controller.DisplayWarningMessage(errorMessage);
}
foreach (var param in filterContext.ActionParameters)
{
if (param.Key.ToLower() == "model" || param.Value is ViewModelBase)
{
viewData.Model = param.Value;
break;
}
}
if (viewData.Model is ViewModelBase)
{
(viewData.Model as ViewModelBase).RebuildModel();
}
filterContext.Result = new ViewResult
{
ViewData = viewData
};
}
}
base.OnActionExecuting(filterContext);
}
}
On an IIS 7.0 server the action filter works as intended and will produce responses like the following for AJAX calls.
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Server: Microsoft-IIS/7.0
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 08 Oct 2013 21:40:36 GMT
Content-Length: 47
The error message I want the end user to see.
However running on IIS 7.5 or later I get responses like the following. Apparently IIS or MVC decides to replace my response body with "Bad Request" and sets the type to text/html. Wondering what is going here, why would it modify the response like this?
HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: text/html
Server: Microsoft-IIS/7.5
X-AspNetMvc-Version: 4.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Tue, 08 Oct 2013 21:50:02 GMT
Content-Length: 11
Bad Request