[HttpDelete]
public HttpResponseMessage Delete(string id)
{
string status = "";
int _id = Convert.ToInt16(id);
tbl_machinedieselInfo data= db.tbl_machinedieselInfo.Where(x=>x.Id==_id).FirstOrDefault();
if (data.Id > 0)
{
db.tbl_machinedieselInfo.Remove(data);
db.SaveChanges();
status = "Deleted";
}
else {
status = "Bad Request";
}
return Request.CreateResponse(HttpStatusCode.OK, status);
}
I try to delete record using above api but it throws an error("HTTP Error 405"), for testing these api I am using postman and fiddler, it works properly on local host but does not work on IIS, please help.
Related
Hi (ref issue)
After setting up the tenant to allow invitation of user from another domain, we are able to invite external users (in set domain) to teams. This works fine when doing it manually, in the GUI.
However, when trying to add an invited user threw the windows graph API, something is not working properly.
Our procedure to invite a user to a team is as follows:
Note we are using application privileges
Invite the user to the tenant (with or without welcome mail)
https://learn.microsoft.com/en-us/graph/api/invitation-post?view=graph-rest-1.0
Add the invited user to the team
https://learn.microsoft.com/en-us/graph/api/group-post-members?view=graph-rest-1.0
Both these calls complete successfully and does not return any error messages. In all the admin GUI’s (AAD, Teams, Exchange) the user is invited and is added to the group.
But the user in question does not receive a welcome mail that he/she has been added to the team. And if the user (given we send a welcome mail in step 1) tries to access http://teams.microsoft.com the user gets notified that he/she does not have permissions and/or does not see the team.
Any tips?
API Permissions
EDIT:
After some investigation, by monitoring the network traffic. It's seems that the missing call, to get properly invited to the team is:
POST https://api.teams.skype.com/emea/beta/teams/($teamurl)/bulkUpdateRoledMembers?allowBotsInChannel=true
where you send in a list of userid (8:orgid:{userid}) and the groupid. (teamurl seems to be the channel id)
{"users":[{"mri":"8:orgid:00000000-5946-0000-87d2-b16b6fdf7a72","role":2}],"groupId":"00000000-2e8b-4d18-0000-394c6a4846d0"}
I have tried to call this from application & delegation, but get 'Unauthorized'. Also I could not find any API permission that granted access to 'api.teams.skype.com'.
I finally figured out how to get an access token to invoke bulkUpdateRoledMembers. It only works if I request an access token for it directly, so no Application Permissions and no On-Behalf-Of Flow.
private static async Task<string> GetAccessTokenForTeams(string tenantId)
{
var client = new PublicClientApplication(
clientId: "d3590ed6-52b3-4102-aeff-aad2292ab01c",
authority: $"https://login.microsoftonline.com/{tenantId}/",
userTokenCache: null);
try
{
var result = await client.AcquireTokenInteractive(new[] { "https://api.spaces.skype.com/user_impersonation" }, null).ExecuteAsync();
return result.AccessToken;
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
}
It turns out you also need a Skypetoken, which you can get very easily with the just acquired access token.
private static async Task<string> GetSkypeToken(string accessToken)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), "Bearer " + accessToken);
using (var response = await client.PostAsync("https://api.teams.skype.com/beta/auth/skypetoken", null))
{
var contentString = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var skypeTokenResponse = JsonConvert.DeserializeObject<SkypeTokenResponse>(contentString);
return skypeTokenResponse.Tokens.SkypeToken;
}
else
{
throw new Exception(response.StatusCode.ToString() + ": " + contentString);
}
}
}
}
private class SkypeTokenResponse
{
public Token Tokens { get; set; }
public class Token
{
public string SkypeToken { get; set; }
public string ExpiresIn { get; set; }
}
}
Then you can finally invoke bulkUpdateRoledMembers by passing both tokens along.
private static async Task<object> bulkUpdateRoledMembers(string accessToken, string skypeToken, string teamUrl, string groupId, string userId)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), "Bearer " + accessToken);
client.DefaultRequestHeaders.Add("X-Skypetoken", skypeToken);
var bodyString = JsonConvert.SerializeObject(new
{
users = new List<object>
{
new
{
mri = "8:orgid:" + userId,
role = 2
}
},
groupId = groupId
});
var body = new StringContent(bodyString, Encoding.UTF8, "application/json");
using (var response = await client.PutAsync($"https://teams.microsoft.com/api/mt/emea/beta/teams/{teamUrl}/bulkUpdateRoledMembers?allowBotsInChannel=true", body))
{
var contentString = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
var jsonresult = JObject.Parse(contentString);
return jsonresult;
}
else
{
throw new Exception(response.StatusCode.ToString() + ": " + contentString);
}
}
}
}
While consuming the web.Api i am getting method not allowed(405). i followed all step but issue is still there. But when I test through soapUi it works well. Please help
Web.Api Declaration:
[Route("ForgotPassword")]
[AcceptVerbs( "POST")]
public ForgotPasswordResponse ForgotPassword(string emailId)
{
AccountInfo accountInfo = _manager.GetUserByEmailId(emailId);
if (accountInfo == null)
return new ForgotPasswordResponse
{
Response = "error",
Message = "Email address not found"
};
return new ForgotPasswordResponse
{
Response = "success",
Message = "password reset link set to registered email id"
};
}
Consuming Service call:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://100.7.11.76");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response12 = client.GetAsync("test.Api/api/account/ForgotPassword?EmailId=" + email + "").Result;
if (response12.IsSuccessStatusCode)
{
string responseString = response12.Content.ReadAsStringAsync().Result;
}
}
Your WebAPI controller ForgotPasswordResponse accepts the verb "POST" and your WebAPI client is invoking it as GET. Hence you get 406: Method not allowed response. Either make your controller accept GET verb or invoke the WebAPI using PostAsJsonAsync method instead of GetAsync.
Try to use Authentication Filters [AllowAnonymous]
[AllowAnonymous]
[Route("ForgotPassword")]
[AcceptVerbs( "POST")]
public ForgotPasswordResponse ForgotPassword(string emailId)
{
AccountInfo accountInfo = _manager.GetUserByEmailId(emailId);
if (accountInfo == null)
return new ForgotPasswordResponse
{
Response = "error",
Message = "Email address not found"
};
return new ForgotPasswordResponse
{
Response = "success",
Message = "password reset link set to registered email id"
};
}
Change the Route attribute to [Route("api/account/ForgotPassword")], change from POST to GET and test your method from a REST client like PostMan first and then use it in your application.
I am trying to read the "session" value in my domain, and I am saving the last visited product id in session. I then take the user to pay online using another "REST" api of another website, but when returning from the api website, my session value gets lost in the browser.
These are my Controller's ActionResults:
Product Details
public ActionResult ProductDetails(int id)
{
Session["LastVisitProductID"] = id;
return View();
}
Pay Details Form
[HttpPost]
public ActionResult PaymentDetailsForm()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.payexample.com/api/pay_online");
request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(paymentform);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
// etc... does request and response, if response is successful payment then
return url to : SuccessPage
return View();
}
Success Page
public ActionResult SuccessPage()
{
int id = Convert.ToInt32(Session["LastVisitProductID"]);
// Here is the problem session value is 0 or null
if (id == 0 || id == null)
{
return RedirectToAction("SomeErrorPage");
}
return View();
}
I wish to know what it is that I am doing wrong, how can I persist "session" in my site even when redirected to another site.
Any help would be great.
This is my controller actionReslt
[ValidateAntiForgeryToken()]
public ActionResult PaymentDetails(PaymentViewModel payment)
{
PaymentModel paymentModel = new PaymentModel();
// AutoMapper.Mapper.CreateMap<PaymentModel, PaymentViewModel>();
if (ModelState.IsValid)
{
CreditCardDetailsModel creditCardDetailsModel = new CreditCardDetailsModel();
creditCardDetailsModel.SecurityId = payment.SecurityId;
creditCardDetailsModel.ExpiryDate = payment.Month + payment.Year;
creditCardDetailsModel.CardNumber = payment.CardNumber;
paymentModel.CreditCardDetails = creditCardDetailsModel;
return RedirectToAction("Payment",paymentModel);
}
return View("FlightBooking");
}
and this is my async method
public async Task<JsonResult> Payment(PaymentModel model)
{
CreateFormOfPaymentReplyModel response = new CreateFormOfPaymentReplyModel();
resource = Constants.Payment;
response = await Post<CreateFormOfPaymentReplyModel>(model);
resource = Constants.PnrConfirm;
var pnrConformStatus = await Get<PNRConfirmResponseModel>();
return new JsonResult { Data = new { status = false, message = response } };
}
and i want to return to Payment method with paymentObject if it is valid but PaymentModel is returning null data and it is showing the error as
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet
Have you tried passing allowget to your return variable?
i.e:
return Json( new { status = false, message = response }, JsonRequestBehavior.AllowGet);
Hope this helps.
I am writing an application that is accepting POST data from a third party service.
When this data is POSTed I must return a 200 HTTP Status Code.
How can I do this from my controller?
In your controller you'd return an HttpStatusCodeResult like this...
[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
// todo: put your processing code here
//If not using MVC5
return new HttpStatusCodeResult(200);
//If using MVC5
return new HttpStatusCodeResult(HttpStatusCode.OK); // OK = 200
}
200 is just the normal HTTP header for a successful request. If that's all you need, just have the controller return new EmptyResult();
You can simply set the status code of the response to 200 like the following
public ActionResult SomeMethod(parameters...)
{
//others code here
...
Response.StatusCode = 200;
return YourObject;
}
[HttpPost]
public JsonResult ContactAdd(ContactViewModel contactViewModel)
{
if (ModelState.IsValid)
{
var job = new Job { Contact = new Contact() };
Mapper.Map(contactViewModel, job);
Mapper.Map(contactViewModel, job.Contact);
_db.Jobs.Add(job);
_db.SaveChanges();
//you do not even need this line of code,200 is the default for ASP.NET MVC as long as no exceptions were thrown
//Response.StatusCode = (int)HttpStatusCode.OK;
return Json(new { jobId = job.JobId });
}
else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { jobId = -1 });
}
}
The way to do this in .NET Core is (at the time of writing) as follows:
public async Task<IActionResult> YourAction(YourModel model)
{
if (ModelState.IsValid)
{
return StatusCode(200);
}
return StatusCode(400);
}
The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.
As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:
return StatusCode((int)HttpStatusCode.OK);
Furthermore, you could also use some of the built in result types. For example:
return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON
Ref. StatusCodeResult - https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1