I am having some troubles with an asp.net WebApi project. I am using the rtm bits.
Within my api controller I have this
[HttpPut]
public Business Update([FromBody]Business business)
{
try
{
if (business.Id == Guid.Empty)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
return _repository.Update(business);
}
catch (Exception ex)
{
log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());
log.Info(string.Format("Update Error Business"));
log.Info(ex);
throw;
}
}
My mvc4 application I am calling this api method from a repository within my application
public static HttpResponseMessage Put(string apiMethod,string baseAddress,object objectData)
{
var myHttpClient = new HttpClient
{
BaseAddress = new Uri(baseAddress)
};
myHttpClient.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue("username", "Password1");
myHttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var put = myHttpClient.PutAsJsonAsync(apiMethod, objectData);
var x = put.Result;
return x;
}
I keep getting a server 500 error. I have a breakpoint on the api controller and its not getting hit. If a manually call the api from a 3rd party tool the api is called.
I have checked all of the basic things but can't seem to figure out whats going on.
Anyone got any tips I can use to figure out whats going wrong?
I am too stuck on a similar scenario. Not sure if it is exactly the case as yours. Generally PUT/DELETE has some issues. Here is my issue (you can decide if it resembles yours):
PUT and DELETE returns 404 for asp.net webapi in Windows 2008 Server IIS 7 and 7.5
Related
I have some legacy framework code that calls a service that I need to replicate in a .NET Core 3.1 solution. The code uses a client built by adding a web reference (ImageService). The code authenticates the user using Membership and sets an authentication cookie that is used by the execution of client methods.
The method below is what I need to replicate in the Core solution. I've created a client in the .NET Core solution also using the WCF web reference. What do I need to do/use to replicate the functionality of the code below?
private static void setImageService(string host, string userId, string password) {
ImageService.ImageService _imageServiceSoapClient = new ImageService.ImageService();
((ClientFormsAuthenticationMembershipProvider) Membership.Provider).ServiceUri = string.Format("https://{0}/ImageService/Authentication_JSON_AppService.axd", host);
((ClientRoleProvider) Roles.Provider).ServiceUri = string.Format("https://{0}/ImageService/Role_JSON_AppService.axd", host);
bool validateUser = Membership.ValidateUser(userId, password);
if (validateUser) {
AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal);
} else {
throw new InvalidCredentialException(string.Format("User {0} not authenticated", userId));
}
_imageServiceSoapClient.CookieContainer = ((ClientFormsIdentity) Thread.CurrentPrincipal.Identity).AuthenticationCookies;
}
the
Lately I joined a project that is using Azure AD Open ID connect authentication code to authenticate with the ASP.Net Core web application.
When I am trying to run it locally I am facing issues with retrieving info with the GetAccountAsync method (Return null). From what I read, I think the code is missing a caching helper to cache the user/application tokens.
public async Task<string> GetUserAccessTokenAsync(string userId)
{
var account = await _app.GetAccountAsync(userId);
try
{
var result = await _app.AcquireTokenSilent(_scopes, account).ExecuteAsync();
return result.AccessToken;
}
// Unable to retrieve the access token silently.
catch (Exception)
{
throw new ServiceException(new Error
{
Code = GraphErrorCode.AuthenticationFailure.ToString(),
Message = "Caller needs to authenticate. Unable to retrieve the access token silently."
});
}
}
If anyone has any idea what I could do to fix this issue Ill be happy to know :)
Thank you!
I have a barebone Service Fabric Application hosting a Asp.net Core 1.1 Web API with Azure Application Gateway as reverse proxy on a Virtual Machine scale set of 5 DS3_V2.
The API have 10 HttpClients with different URLs injected via Dependency Injection.
A simple foreach cycle in a method call 10 Httpclients in parallel:
var cts = new CancellationTokenSource();
cts.CancelAfter(600);
//Logic for asyncronously parallel calling the Call method below
public async Task<MyResponse> Call(CancellationTokenSource cts, HttpClient client, string endpoint )
{
var endpoint = "finalpartOfThendpoint";
var jsonRequest = "jsonrequest";
try
{
var content = new StringContent(jsonRequest, Encoding.UTF8, "application/json");
await content.LoadIntoBufferAsync();
if (cts.Token.IsCancellationRequested)
{
return new MyResponse("Token Canceled");
}
var response = await client.PostAsync(endpoint, content, cts.Token);
if (response.IsSuccessStatusCode && ((int)response.StatusCode != 204))
{
//do something with response and return
return MyResponse("Response Ok")
}
return MyResponse("No response")
}
catch (OperationCanceledException e)
{
return new MyResponse("Timeout");
}
}
There is a single CancellationToken for all calls.
After 600ms, the still pending HttpCalls are canceled and a response is sent back anyway.
In local and in production all works perfectly, all endpoints are called and return in time, rarely one is canceled before the timeout.
But when the number of concurrent connections reach 30+, ALL calls timeout no matter what, until I reduce the load.
Does Asp.net Core have a connection limit?
This is how I create the HttpClients in a custom factory for injection in the main Controller:
public static HttpClient CreateClient(string endpoint)
{
var client = new HttpClient
{
BaseAddress = new Uri(endpoint)
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
All the Httpclients are reused and static.
The same exact code works perfectly on a Asp.net Web API 2 hosted on OWIN in Service Fabric. The problem is only with Asp.net Core 1.1
I saw online to create a HttpClientHandler, but there is no parameter for concurrent connections.
What can I do to investigate further?
No exception are thrown but the OperationcanceledException and If I remove the CancellationToken the calls are stuck and the CPU goes to 100%, basically 30 connections destroy the power of 5 quad core servers.
This has something to do to the number of calls going out of Kestrel.
UPDATE
I tried with WebListener and the problem is still present, so it's not Kestrel, but Asp.net Core
I figured it out.
Asp.net core still have some HttpClient limits for the connection to the same server like the old Asp.net WebAPI.
It's poor documented but the old ServicepointManager option for maxconnections must now be passed via HttpClientHandler.
I just create HttpClient like this and the problem vanished.
var config = new HttpClientHandler()
{
MaxConnectionsPerServer = int.MaxValue
};
var client = new HttpClient(config)
{
BaseAddress = new Uri('url here')
};
Really if someone of the team is reading, this should be the default.
I am using mvc4 as my web application which inherits a WCF service i have an Entity framework and used Code first for database Now, Entity layer is inherited to both MVC as well as to WCF but Data Access layer is only inherited to the WCF, Now when ever i call the WCF method from my controller the method is called nicely and the method works fine into the WCF and returns the expected result but when it returns result to the MVC application it throws an exception of "The underlying connection was closed: An unexpected error occurred on a receive." can anyone please help me out, following is the code respectively:-
for Controller class
public ActionResult CustomerSearch()
{
APIServiceDaman.Customer ObjTestEn = new APIServiceDaman.Customer();
using (Objjj = new APIServiceDaman.Service1())
{
var ObjTestEn2 = Objjj.GetUserDetails(1, true);
}
return View(ObjTestEn);
}
for WCF:-
public X.Entities.Customer GetUserDetails(int CustomerID)
{
X.Entities.Customer objtest = new X.Entities.Customer();
using (ObjCustomerEvidence = new CustomerManager())
{
objtest = ObjCustomerEvidence.GetCustomerByID(CustomerID);
}
return objtest;
}
for DataAccess Layer:-
public Entities.Customer GetCustomerByID(int ID)
{
return DBContext.Customer.Where(c => c.ID == ID).FirstOrDefault();
}
First of all check your web.config setting for executionTimeout and maxRequestLength on both side WCF and your MVC4 client. for more information on this please refer this below link there is a good answer given by jlchereau, follow this steps and try to check it out again, it might help you out. also try to enable WCF tracing (Tracing) and find out the root of exception it will help you a lot to resolve your issue.
http://velodocaddin.codeplex.com/discussions/40792
I am writing a fairly simple MVC3 application that allows a user to retrieve and modify some configuration data held by a WCF service. The configuration data will not change very often but needs to be maintainable by the user.
Once the user is happy with the configuration, they will launch some processing from the UI or by the scheduled execution of a VB script.
I'm fairly new to WCF and even newer to MVC3 but I'd like to make all the comms to and from the service RESTful. Is this a good thing to do?
I'd been planning to perform the service communications from the MVC controller. This would make a HTTP Get request to retrieve the current configuration and a HTTP Post to apply the modified configuration. I'd also use a Get request to launch the processing.
Could anyone provide an example (or point me in the direction) of how I should be doing this?
Please follow the below links for some sample code to build a RESTful WCF Service and the how the client would access the service.
Link to create a RESTful service: here
Link to create a .NET client that consumes the RESTful service : here
Hope the information helps you out.
If you are the owner of web service, you can directly reference implementation of service in your mvc project and use it without web reference. You can write some like this:
// example of ws
public class Service1 : IService1
{
public string GetData( int value )
{
return string.Format( "You entered: {0}", value );
}
public CompositeType GetDataUsingDataContract( CompositeType composite )
{
if( composite == null )
{
throw new ArgumentNullException( "composite" );
}
if( composite.BoolValue )
{
composite.StringValue += "Suffix";
}
return composite;
}
}
// example of mvc action
public class HomeController : Controller
{
public ActionResult Index()
{
IService1 service = new Service1();
service.GetDataUsingDataContract(....)
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
The simplest answer I've found was here:, using the channel factory.
I still don't know if it's the best way but it left my code looking clean enough. Below is a sample from my controller.
public ActionResult Index()
{
SettingsModel config = null;
// Set up a channel factory to use the webHTTPBinding
using (WebChannelFactory<IChangeService> serviceChannel =
new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl )))
{
IChangeService channel = serviceChannel.CreateChannel();
config = channel.GetSysConfig();
}
ViewBag.Message = "Service Configuration";
return View(config);
}